﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using umbraco.BusinessLogic;
using umbraco;

namespace TheOutfield.UmbExt.IE9Extensions.Filters
{
    public class IE9ExtensionsFilter : Stream
    {
        public IE9ExtensionsFilter(Stream stream)
        {
            _stream = stream;
        }

        private Stream _stream;

        #region Properties

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        #endregion

        #region Methods

        public override void Flush()
        {
            _stream.Flush();
        }

        public override long Length
        {
            get { return 0; }
        }

        private long _position;
        public override long Position
        {
            get { return _position; }
            set { _position = value; }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _stream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return _stream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            _stream.SetLength(value);
        }

        public override void Close()
        {
            _stream.Close();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            byte[] data = new byte[count];
            Buffer.BlockCopy(buffer, offset, data, 0, count);
            string html = System.Text.Encoding.Default.GetString(buffer);

            if (HttpContext.Current != null)
            {
                var sb = new StringBuilder();
                sb.AppendFormat(
                    @"<link rel='icon' href='{0}' type='image/x-icon'>
                <link rel='shortcut icon' href='{0}' type='image/x-icon'> 
                <meta name='application-name' content='Umbraco CMS - {1}' />
                <meta name='msapplication-tooltip' content='Umbraco CMS - {1}' />
                <meta name='msapplication-window' content='width=1024;height=768' />
                <meta name='msapplication-navbutton-color' content='#f36f21' />
                <meta name='msapplication-starturl' content='./umbraco.aspx' />",
                    GetFullyQualifiedAppPath() +
                    GlobalSettings.Path.Replace("~/", HttpContext.Current.Request.ApplicationPath) + "/images/umb.ico",
                    HttpContext.Current.Request.Url.Host.ToLower().Replace("www.", ""));

                var user = User.GetCurrent();
                if (user != null && user.Applications != null && user.Applications.Length > 0)
                {
                    foreach (var app in user.Applications)
                    {
                        sb.AppendFormat(
                            @"<meta name='msapplication-task' content='name={0}; action-uri={1}; icon-uri={2}' />",
                            ui.Text("sections", app.alias, user),
                            GetFullyQualifiedAppPath() +
                            GlobalSettings.Path.Replace("~/", HttpContext.Current.Request.ApplicationPath) +
                            "/umbraco.aspx#" + app.alias,
                            File.Exists(HttpContext.Current.Server.MapPath("/umbraco/images/task_" + app.alias + ".ico"))
                                ? "/umbraco/images/task_" + app.alias + ".ico"
                                : "/umbraco/images/task_default.ico");
                    }
                }

                html = html.Replace(@"</head>", sb.ToString() + @"
                </head>");
            }

            byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
            _stream.Write(outdata, 0, outdata.GetLength(0));
        }

        private string GetFullyQualifiedAppPath()
        {
            var appPath = "";
            var context = HttpContext.Current;

            if (context != null)
            {
                appPath = string.Format("{0}://{1}{2}{3}",
                    context.Request.Url.Scheme,
                    context.Request.Url.Host,
                    (context.Request.Url.Port == 80) ? string.Empty : ":" + context.Request.Url.Port,
                    context.Request.ApplicationPath);
            }

            return appPath.Trim('/');
        }

        #endregion
    }
}